package com.example.redis.controller;

import com.example.redis.DTO.WeChatMiniAppAuthResponse;
import com.example.redis.common.ResponseResult;
import com.example.redis.config.PropertyConfig;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequiredArgsConstructor
@Slf4j
public class test {
    private final RedisTemplate redisTemplate;

    private final PropertyConfig propertyConfig;

    @GetMapping("set")
    public ResponseResult set(){
        log.info("设置redis数据测试");
        Map<String, Object> map=new HashMap<>();
        map.put("1",1);
        map.put("2",2);
        redisTemplate.opsForValue().set("key",map);
        log.info("测试成功");
        return ResponseResult.success();
    }

    @GetMapping("get")
    public ResponseResult get(){
        log.info("获取redis数据测试");
        Object res=redisTemplate.opsForValue().get("key");
        Map<String,Object> map=(HashMap<String,Object>)res;
        return ResponseResult.success(map.get("1"));
    }

    @GetMapping("/login")
    public ResponseEntity<WeChatMiniAppAuthResponse> login(@RequestParam("code") String code,
                                                            String avator,
                                                            String name) {
        try {
            // 调用微信提供的auth.code2Session接口换取session_key和openid等信息
            String url = "https://api.weixin.qq.com/sns/jscode2session?" +
                    "appid=" + propertyConfig.getAppId() +
                    "&secret=" + propertyConfig.getSecret() +
                    "&js_code=" + code +
                    "&grant_type=authorization_code";
            System.out.println(url);
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
            String responseBody = responseEntity.getBody();

            ObjectMapper objectMapper = new ObjectMapper();
            WeChatMiniAppAuthResponse authResponse = objectMapper.readValue(responseBody, WeChatMiniAppAuthResponse.class);

            return ResponseEntity.ok(authResponse);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
}
